<?php
/**
 * CreateTime: 2023/3/30 10:49
 */

namespace App\Http\Controllers\Import;

use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\AppFunc;
use App\Func\CurlFunc;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Http\Controllers\Controller;
use App\Imports\CasesImport;
use App\Jobs\ProcessCaseImport;
use App\Models\File\FileModel;
use App\Models\ImportTask;
use App\Models\MeClient\MeClientModel;
use App\Service\MeCaseSerice\ImportLawCase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use PHPUnit\Exception;

class ImportController extends Controller
{
    public function importCaseV2($clientId)
    {
        $allow = ['xlsx', 'xls']; // 同时支持xlsx和xls
        $mimeArr = [
            "xls" => "application/vnd.ms-excel",
            "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        ];

        // 获取文件
        $file = request()->file('file');
        if (!$file->isValid()) {
            return ResponseFunc::returnJson(
                'error',
                null,
                '文件上传失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

        // 获取mimeType和文件后缀名
        $mimeType = $file->getMimeType();
        $ext = strtolower($file->getClientOriginalExtension());

        // 验证文件类型
        if (!in_array($ext, $allow) || ($mimeArr[$ext] ?? '') != $mimeType) {
            return ResponseFunc::returnJson(
                'error',
                null,
                '文件类型错误，仅支持xlsx和xls格式',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

        try {
//            Excel::import(new CasesImport($clientId,TokenFuc::getCurrentStaffInfo()['staff_id']),$file);
            // 保存文件到临时目录（保留扩展名，解决类型检测问题）
            $tempDir = storage_path('app/temp/');
            if (!is_dir($tempDir)) {
                mkdir($tempDir, 0755, true);
            }
            $tempFileName = uniqid() . '.' . $ext;
            $tempFilePath = $tempDir . $tempFileName;
            $file->move($tempDir, $tempFileName);
            $owner_id = TokenFuc::getCurrentStaffInfo()['staff_id'] ?? 0;
            // 创建并分发任务
            $job = new ProcessCaseImport(
                $tempFilePath,
                $clientId,
                $owner_id,
                $file->getClientOriginalName(), // 传递原始文件名
                $ext // 显式传递文件扩展名
            );
            dispatch($job);

            return ResponseFunc::returnJson(
                'ok',
                [
                    'task_id' => $job->getTaskId(),
                ],
                '导入任务已提交',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        } catch (Exception $error) {
            return ResponseFunc::returnJson(
                'error',
                null,
                $error->getMessage(),
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function checkProgress()
    {
        // 验证任务ID
        $taskId = request()->task_id ?? "";

        // 查询任务状态
        $task = ImportTask::where('task_id', $taskId)->first();
        if (!$task) {
            return ResponseFunc::returnJson(
                'error',
                null,
                '任务不存在',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

        // 计算进度百分比（避免除零错误）
        $progress = $task->total_rows > 0
            ? min(100, (int)(($task->processed_rows / $task->total_rows) * 100))
            : 0;

        return ResponseFunc::returnJson(
            'ok',
            [
                'task_id' => $task->task_id,
                'status' => $task->status, // pending/processing/success/failed
            ],
            '查询',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
        // 返回进度信息
    }


    public function uploadExcel($clientId): \Illuminate\Http\JsonResponse
    {
        // 根据用户clientId获取当前用户的uuid
        $uuid = (new MeClientModel())->getById($clientId,['client_union_id'])['client_union_id'] ?? false;
        if(!$uuid){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前用户未绑定唯一id',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

        $fileModel = new FileModel();
        $allow = [
            'xlsx',
        ];
        $mimeArr = [
            "xls" => "application/vnd.ms-excel",	// Microsoft Excel
            "xlsx"=> "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        ];
        // 获取文件
        $file = request()->file('file');
        $hasExtra = @request()->get('extra');
        $formatExtra = [];
        if($hasExtra){
            $formatExtra = json_decode($hasExtra,true);
        }

        try {
            // 获取文件原始名称
            $originalName = $file->getClientOriginalName();
            // 获取文件临时存储位置
            $path = $file->getRealPath();
            // 获取mimeType
            $mimeType = $file->getMimeType();
            // 获取文件后缀名
            $ext = $file->getClientOriginalExtension();
            $err = $file->getError();
            if($err){
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    '文件上传失败',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '文件上传失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        // 生成文件夹
        $dir = date("Ymd");
        // 生成加密后的文件地址
        $encryptionFileUrl = "file".DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.md5($originalName.time()).".".$ext;
        if(!in_array($ext,$allow)|| $mimeArr[$ext]!=$mimeType){
            return ResponseFunc::returnJson(
                'error',
                null,
                '文件类型错误',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        try {
            $res = Storage::disk('local')->put($encryptionFileUrl,file_get_contents($path));
            if(!$res){
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    '上传文件失败',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }
            DB::beginTransaction();
            try {
                $id = $fileModel->insertGetId(
                    [
                        'file_name'=>$originalName,
                        'file_url'=>$encryptionFileUrl,
                        'file_ext'=>$ext,
                        'file_mime_type' => $mimeType,
                        'created_at' => time()
                    ]
                );
                DB::commit();
            }catch (Exception $exception){
                DB::rollBack();
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    $exception->getMessage(),
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }
            $filePath = Storage::path($encryptionFileUrl);
            // 加密file
            $filePath = (new ImportLawCase())->urlImportEncode($filePath);


            return ResponseFunc::returnJson(
                'ok',
                [
                    'file_id' => $id,
                    'client_id' => $clientId,
                    'uuid' => $uuid,
                    'owner_id' => TokenFuc::getCurrentStaffInfo()['staff_id'] ?? 0,
                    'file_path' => $filePath,
                    'file_name'=>$originalName,
                    'file_ext'=>$ext,
                    'file_mime_type' => $mimeType,
                    'created_at' => time()
                ],
                '上传文件成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (Exception $error){
            return ResponseFunc::returnJson(
                'error',
                null,
                $error->getMessage(),
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function checkExcel(){
        $data = request()->all();
        $excel_file_path = urlencode($data['excel_file_path']);
        $extra_parameter = urlencode($data['extra_parameter']);
        $fileInfo = json_decode($data['extra_parameter'],true);
        // 模板导入检查
//        $ef = new ExcelFunc();
//        $excelFirstRow = $ef->readFirstRow($fileInfo['file_id']);
//        if($excelFirstRow['ok'] == false){
//            return ResponseFunc::returnJson(
//                'error',
//                null,
//                $excelFirstRow['msg'],
//                ResponseStatusConsts::OK_200_RESPONSE_STATUS
//            );
//        }
//
//
//        $clientModel = new MeClientModel();
//        $clientInfo = $clientModel->getById($fileInfo['client_id'],['client_custom_json','client_map_excel_file_column_header_to_database_table_field']);
//        // 初始化变量
//        $clientCustomFmtArr = [];
//        $clientExcelFmtArr = [];
//
//        $dataExcelImportConfigHeader = [];
//
//        if($clientInfo['client_map_excel_file_column_header_to_database_table_field']!=null){
//            $clientExcelFmtArr = json_decode($clientInfo['client_map_excel_file_column_header_to_database_table_field'],true);
//            foreach($clientExcelFmtArr['map_excel_file_column_header_to_database_table_field'] as $value){
//                if($value['title']){
//                    $dataExcelImportConfigHeader[] = $value['title'];
//                }
//            }
////            foreach($clientExcelFmtArr['map_excel_file_column_header_to_database_table_field_custom'] as $value){
//            foreach($clientExcelFmtArr['map_excel_file_column_header_to_database_table_field'] as $value){
//                if($value['title']){
//                    $dataExcelImportConfigHeader[] = $value['title'];
//                }
//            }
//        }
//
//        $diff =  array_diff($dataExcelImportConfigHeader, $excelFirstRow);
//
//        if($diff){
//            return ResponseFunc::returnJson(
//                'error',
//                null,
//                "文件与配置的模板不符【".implode(',',$diff)."】",
//                ResponseStatusConsts::OK_200_RESPONSE_STATUS
//            );
//        }

        $url = AppFunc::getSystemConfig()::HTTP_BASE_URL.":39350/convert.excel.2.redis.list/create_new_convert_workflow?excel_file_path=$excel_file_path&extra_parameter=$extra_parameter";
        return CurlFunc::CurlGet($url);
    }

}